'''
Created on 2010-10-25
@author: Q
'''
import os,sys, string,time, FaultTolerance, ConfigBase
import  traceback, File
from Performance import Performance
import shutil
maxYear = 1
path = ""
def getPath():
    global path
    if path == "":
        path = ConfigBase.getAutoSavePath();
#        if sys.platform == "win32":
#            path = "C:\\Users\\Q\\Documents\\OpenTTD\\save\\autosave"
#        elif sys.platform.find("linux") >=0 :
#            #path = "/home/sq/.openttd/save/autosave"
#    #        path = "/home/sshen/.openttd/save/autosave"
#            path = "/var/tmp/sshen/run/save/autosave"
#    #        path = "/local/sshen/.openttd/save/autosave"
    return path

def getProcess(processName):
    if sys.platform == "win32":
        file = os.popen("ps")
        lines = file.readlines()
        for line in lines:
            if(line.find(processName) > 0):
                words = string.split(line)
                if words[0].find("I") == 0 :
                    return words[3]
                else: 
                    return words[0]
    elif sys.platform.find("linux") >= 0:
       file = os.popen("ps ax|grep " + processName)
       lines = file.readlines()
       if(len(lines) == 0):
           return None
       for line in lines:
           return string.split(line)[0]

def killOpenTTD(file, expId, expName, factor, hostname, targetPath, openFT=False, cwd=os.getcwd()):
    os.chdir(cwd)
    path = getPath()
    while True:
#        print path
        if(is10Years(file,expId, expName, factor, hostname, targetPath, openFT)):
#        if(True):
#            if(sys.platform == "win32"):
#                id = getProcess("openttd")
#                kill(id)
#                os.system("pskill openttd");
#                os.system("pskill tshark");
#            else:
                killAllOpenTTD()
                killTshark()
                break
#        os.system("echo " + targetPath + " >>~/targetpath.txt")
#        os.system("echo getPath" + path + " >>~/filePath.txt")
        time.sleep(5)
#        print "sleeping"

def killAllOpenTTD():
    cmd = "killall -9 openttd"
    if sys.platform == "win32":
        cmd = "pskill openttd"
    print cmd;
    os.system(cmd)
    
def killTshark():
    if sys.platform == "win32":
        os.system("pskill tshark")
    elif sys.platform.find("linux")>=0:
        os.system("killall -9 tshark")
#    return True

#Todo add some staic to get the time of each year        
def is10Years(file, expId, expName, factor, hostname,targetPath, openFT):
    try:
        path = getPath()
        filename = os.path.join(path, "autosave%d"%(maxYear-1) + ".sav")
    #    print filename
        if os.path.exists(filename):
            """
            if the exp is client/server app, the server will sleep half minute to let all the client 
            dump their save map and exit; after that the server could exit 
            """
            if expName[0] == "2" or expName == "5":
                time.sleep(30) 
            array = []
            for fn in os.listdir(path):
                if fn.find("autosave") == -1:
                    continue
                f = os.stat(os.path.join(path, fn))
                pth = string.atoi(fn[len("autosave"): fn.find(".")])
                if(pth>(maxYear-1)):
                    continue;
                print >> file, pth, fn, f.st_ctime
#            if(sys.platform != "win32"):
            for fn in os.listdir(path):
                if openFT == True and fn.endswith(".sav") and fn.find("autosave") >=0 and sys.platform != "win32":
                    FaultTolerance.clientDump(expName, fn, path, "%d_"%expId + expName + "_%d_"%factor + hostname + "_")
                newfn = "%d_"%expId + expName + "_%d_"%factor + hostname + "_" + fn;
                File.newDir(targetPath);
                print "moving", os.path.join(path, fn), os.path.join(targetPath,newfn)
                shutil.copy(os.path.join(path, fn), os.path.join(targetPath,newfn));
                os.remove(os.path.join(path, fn))
#            cmd = "mv " + os.path.join(path, fn) + " "+ os.path.join(targetPath,newfn)
##            os.system("echo \"" + cmd + "\" >>~/mv.txt")    
#            print cmd
#            os.system(cmd)
    #            array.insert(pth, f.st_ctime)   
    #        for pth in xrange(0, maxYear/1):
    #            print >> file, pth, array[pth]
    #        os.system("rm /var/tmp/sshen/save/autosave/*")
            return True
        else :
            return False
    except Exception, e:
        exstr   =   traceback.format_exc()
        print   exstr 
        return True;

if __name__=="__main__":
    print "11"
#    pid = getProcess("openttd")
#    print pid
#    file = open("c:\\ttt", 'w')
#    print is10Years(file)
#    print string.split("   0   1 ")[0]
    #os.system("kill " + pid)